package com.friend.joey.applicationfriend.Fragments;


import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.friend.joey.applicationfriend.Classes.AlertMessage;
import com.friend.joey.applicationfriend.Classes.Msgtalk;
import com.friend.joey.applicationfriend.Database.MyDatabaseHelper;
import com.friend.joey.applicationfriend.MainActivity;
import com.friend.joey.applicationfriend.R;
import com.friend.joey.applicationfriend.Adapters.RememAdapter;
import com.friend.joey.applicationfriend.Classes.RememRecord;
import com.friend.joey.applicationfriend.Classes.TimeDeal;

import java.util.ArrayList;
import java.util.List;

import static android.R.attr.inset;
import static android.R.attr.type;
import static com.baidu.location.h.j.t;


/**
 * Created by Joey on 2017/4/20.
 */

public class FragmentForget extends Fragment {

    private List<RememRecord> remList = new ArrayList<>();//备忘消息
    private Button bnew;
    private TextView txtLog;
    private MainActivity mactivity;
    private RememAdapter adapter;
    private RecyclerView remRecyclerView;
    private Toolbar toolbar;
    private TimePicker tp;


    //展示界面与变量初始化
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_forget, container, false);
        txtLog=(TextView)view.findViewById(R.id.txt_bLog);
        mactivity =(MainActivity)getActivity();
        remRecyclerView = (RecyclerView)view.findViewById(R.id.rem_recycler_view);
        toolbar=(Toolbar)view.findViewById(R.id.toolbarForget);//

        return view;
    }

    //响应函数等
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //
        setHasOptionsMenu(true);
        if (toolbar != null) {
            toolbar.setTitle("  ");
            toolbar.setNavigationIcon(R.drawable.computer3);
        }
        mactivity.setSupportActionBar(toolbar);

        //展示备忘列表
        initRems();
        //txtLog.setText(remList.get(0).toString());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        remRecyclerView.setLayoutManager(layoutManager);
        adapter = new RememAdapter(remList);
        adapter.setOnRemCallbackListener(new RememAdapter.onRemCallback(){
            @Override
            public void onDeleteclick(int itempostion) {
                //Toast.makeText(mactivity,String.valueOf(itempostion),Toast.LENGTH_SHORT).show();
                mactivity.deleteFromDatabase(remList.get(itempostion));
                remList.remove(itempostion);
                adapter.notifyItemRemoved(itempostion);
                adapter.notifyItemRangeChanged(itempostion,remList.size()-itempostion);
                //remRecyclerView.scrollToPosition(remList.size()-1);//定位到最后一行
            }

            @Override
            public void onShowclick() {

            }
        });
        remRecyclerView.setAdapter(adapter);

    }

    //标题菜单栏
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.forget_menu, menu);
        MenuItemCompat.setShowAsAction(menu.findItem(R.id.forget_add),MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        super.onCreateOptionsMenu(menu, inflater);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.forget_add:
                Intent intent = new Intent();
                intent.setAction("android.intent.action.FFNEW");
                intent.putExtra("theme",mactivity.theme);
                startActivityForResult(intent,1);
                break;
            case android.R.id.home:
                mactivity.showDrawer();
                break;
        }
        return true;
    }

    //Activity回调函数
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Boolean add=data.getExtras().getBoolean("add");
        if(add) {
            String rtitle = data.getStringExtra("title");
            Toast.makeText(mactivity,rtitle,Toast.LENGTH_SHORT).show();
            String rcontent = data.getExtras().getString("content");
            Boolean isChecked=data.getExtras().getBoolean("isChecked");
            RememRecord rem1;
            if(isChecked){
                TimeDeal setTime=new TimeDeal(data.getIntExtra("year",0),
                        data.getIntExtra("month",0),
                        data.getIntExtra("day",0),
                        data.getIntExtra("hour",0),
                        data.getIntExtra("min",0));
                int alertId=(int)data.getExtras().getLong("alertid");
                rem1=new RememRecord(rtitle,rcontent,setTime,alertId);
                remList.add(rem1);
                //添加闹钟
                addAlert(data.getExtras().getLong("alertid"),rtitle,rcontent);
            }else{
                rem1=new RememRecord(rtitle,rcontent,RememRecord.NOT_ALERT);
                remList.add(rem1);
            }
            mactivity.insertIntoDatabase(rem1);
            setAlertMessage("添加备忘","标题："+rtitle+" 内容："+rcontent);
            adapter.notifyItemChanged(remList.size()-1);//有新消息时刷新显示
        }
    }

    public void addAlert(long time,String title,String content){
        mactivity.addAlet(time,title,content);
    }
    public void cancelAlert(){

    }
    public void setAlertMessage(String title,String content){
        AlertMessage alertMessage=new AlertMessage(AlertMessage.TYPE_FORGET,title,content);
        mactivity.insertIntoDatabase(alertMessage);
    }

    //初始化备忘录列表
    private void initRems(){
        RememRecord rem0;
        MyDatabaseHelper dbHelper = new MyDatabaseHelper(mactivity,"TestTalk.db",null,2);//数据库
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("forget",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            while(cursor.moveToNext())
            {
                String title= cursor.getString(cursor.getColumnIndex("title"));
                String content=cursor.getString(cursor.getColumnIndex("content"));
                String addtime=cursor.getString(cursor.getColumnIndex("addtime"));
                int dataType=cursor.getInt(cursor.getColumnIndex("type"));
                int id=cursor.getInt(cursor.getColumnIndex("id"));
                if(dataType==RememRecord.NOT_ALERT){
                    rem0=new RememRecord(id,title,content,addtime,dataType);
                    remList.add(rem0);
                }else if(dataType==RememRecord.SET_ALERT){
                    String alerttime=cursor.getString(cursor.getColumnIndex("alerttime"));
                    int alertid=cursor.getInt(cursor.getColumnIndex("addid"));
                    rem0=new RememRecord(id,title,content,addtime,dataType,alerttime,alertid);
                    remList.add(rem0);
                }
            }
        }
        else{
            RememRecord rem1=new RememRecord("吃药","止咳糖浆",RememRecord.NOT_ALERT);
            remList.add(rem1);
            RememRecord rem2=new RememRecord("看电视","京剧大赏",RememRecord.NOT_ALERT);
            remList.add(rem2);
            RememRecord rem3=new RememRecord("吃药3","止咳糖浆3",RememRecord.NOT_ALERT);
            remList.add(rem3);
            Toast.makeText(mactivity, "数据库未获取到信息", Toast.LENGTH_SHORT).show();
        }
    }

    //加载fragment类
    public static FragmentForget newInstance(String arg){
        FragmentForget fragmentMe = new FragmentForget();
        Bundle args = new Bundle();
        args.putString("fForget", arg);
        fragmentMe.setArguments(args);
        return fragmentMe;
    }
}
